'use strict';

angular.module('com.dcos.app').directive('timer', function () {
	return {
		restrict: 'EA',
		scope: {
			addtime:'=',
			nowtime:'=',
			finishtime: '=',
			starttime: '=',
			status: '=',
		},
		link: function (scope, element,attrs) {
			var timerInterval=null;
				if(scope.status!="1") {
					clearInterval(timerInterval);
					element.html("耗时:"+fnFormatDate(scope.finishtime,scope.starttime,0));
				}
				else{
				    timerInterval = setInterval(function () {
						if(scope.starttime) {
	                       var result=fnFormatDate(scope.nowtime,scope.starttime,scope.addtime);
						   scope.addtime+=1000;
					       element.html("耗时:"+result);
						}else{
							element.html("等待执行...");
						}
				    }, 1000);
				}


			function fnFormatDate (finishtime,datetime,addtime) {
				var beginTime = Date.parse(new Date(datetime));
				var nowTime = Date.parse(new Date(finishtime));//+addtime;

				var _days = Math.floor((nowTime - beginTime) / (24 * 3600 * 1000)).toString();
				_days = (_days!="0" ? (_days+"天") : "");

				var _leave1 = (nowTime - beginTime) % (24 * 3600 * 1000);
				var _hours = Math.floor((nowTime - beginTime) / (24 * 3600 * 1000)).toString();
				_hours = (_hours!="0" ? (_hours+"小时") : (_days!=""?"0小时":""));

				var _leave2 = (nowTime - beginTime) % (3600 * 1000);
				var _minutes = Math.floor(_leave2 / (60 * 1000)).toString();
				_minutes = (_minutes!="0" ? (_minutes+"分") : (_hours!=""?"0分":""));

				var _leave3 = _leave2 % (60 * 1000);
				var _seconds = Math.round(_leave3 / 1000).toString();
				_seconds = (_seconds!="0" ? (_seconds+"秒") : (_minutes!=""?"0秒":""));

				return _days +_hours + _minutes +  _seconds;
			}
		}
	}
});
